package com.ja.openchat.viewmodels;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.text.TextUtils;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;

import com.google.gson.JsonObject;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.ja.openchat.R;
import com.ja.openchat.ui.contact.search.PublicSearchFragment;
import com.ja.openchat.ui.message.MsgFragment;
import com.ja.openchat.ui.message.adapter.RecentMessageListAdapter;
import com.zy.openchat.App;
import com.zy.openchat.Constants;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.group.SuperGroupInfo;
import com.zy.openchat.core.model.message.ChatInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.ChatComparator;
import com.zy.openchat.util.Common;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import me.goldze.mvvmhabit.base.BaseModel;
import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;

public class MsgViewModel extends BaseViewModel {

    private Context mContext;
    private RecentMessageListAdapter recentMessageListAdapter;

    public MsgViewModel(@NonNull Application application, BaseModel model) {
        super(application, model);

    }

    public ObservableField<String> fragmentTitle = new ObservableField<>("");
    public ObservableField<String> connect_state = new ObservableField<>("");
    public ObservableField<Boolean> isShowState = new ObservableField<>(false);
    public ObservableField<Boolean> isEmptyView = new ObservableField<>(false);

    public ObservableField<List<ChatInfo>> chatList = new ObservableField<>(new ArrayList<>());



    public BindingCommand searchClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            //跳转搜索页
//            startActivity(PublicChatSearchActivity.class);
            startContainerActivity(PublicSearchFragment.class.getCanonicalName());
        }
    });

    public BindingCommand noticeLayoutClick = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            if(mContext!=null){
                XXPermissions.startPermissionActivity((Activity) mContext, Permission.NOTIFICATION_SERVICE);
            }

        }
    });


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTgEvent(final TgEvent tg_event) {
        switch (tg_event.event) {
            case EUser_Td_Connection_State_Changed:
                //连接状态变更
                refreshConnectionState();
                //todo wangyutao
                //拉取离线音视频通话
                break;
            case EUser_Td_Chat_List_Changed:
            case EUser_Td_Chat_Last_Message_Changed:
            case EUser_Td_UpdateContactInfo:
            case EUser_Td_Chat_Changed:
                //列表会话数量或者排序变化，需要重新获取刷新页面
                stopRefreshTimer();
                startRefreshTimer();
                break;
            case EUser_Td_Chat_Title_Changed:
            case EUser_Td_Chat_Photo_Changed:
            case EUser_Td_Chat_Permissions_Changed:
                //仅内容变化，不涉及排序，直接刷新页面
                recentMessageListAdapter.notifyDataSetChanged();

                break;
            case EUser_Td_Contact_Photo_Ok:
            case EUser_Td_Group_Photo_Ok:
            case EUser_Td_AddNewContactInfo:
            case EUser_Td_Chat_OutMessage_Readed:
                //仅内容变化，不涉及排序，直接刷新页面
                recentMessageListAdapter.notifyDataSetChanged();
                break;
            case EUser_Td_Group_User_Nick_Name_GET:
                if(tg_event.data!=null&&tg_event.data instanceof Long){
                    long chatId = (Long)tg_event.data;
                    int length = recentMessageListAdapter.getData().size();
                    for(int i = 0;i<length;i++){
                        if(recentMessageListAdapter.getItem(i).chatId() == chatId){
                            recentMessageListAdapter.notifyItemChanged(i,Constants.Notify_User_Name_Type);
                            break;
                        }
                    }
                }
                break;
            case EUser_Td_Remove_Contact:
                if(tg_event.data!=null&&tg_event.data instanceof Long) {
                    long userId = (Long) tg_event.data;
                    int length = recentMessageListAdapter.getData().size();
                    for(int i = 0;i<length;i++){
                        ChatInfo chatInfo = recentMessageListAdapter.getItem(i);
                        if(!chatInfo.isGroup()&&chatInfo.userId() == userId){
                            doDeleteChat(null,chatInfo);
                        }
                    }
                }
                break;
        }
    }


    //刷新定时器，防止短时间内大量refresh ui事件
    private Timer timerRefreshTask = null;

    public void startRefreshTimer() {
        if (timerRefreshTask == null) {
            timerRefreshTask = new Timer();
            timerRefreshTask.schedule(new TimerTask() {
                @Override
                public void run() {
                    recentMessageListAdapter.getRecyclerView().post(new Runnable() {
                        @Override
                        public void run() {
                            stopRefreshTimer();
                            resetChatList();
                        }
                    });
                }
            }, 100);
        }
    }

    public void stopRefreshTimer() {
        if (timerRefreshTask != null) {
            timerRefreshTask.cancel();
            timerRefreshTask = null;
        }
    }


    public void refreshConnectionState() {
        TelegramManager.GoUserConnectionState state = TelegramManager.getTelegramManager().getTgData().getUserConnectionState();
        switch (state) {
            case GoUserConnectionState_StateReady:
                isShowState.set(false);
                fragmentTitle.set(getApplication().getResources().getString(R.string.fragment_title));
                break;
            case GoUserConnectionState_Updating:
                isShowState.set(true);
                connect_state.set(getApplication().getResources().getString(R.string.tg_connection_state_updating));
                break;
            case GoUserConnectionState_Connecting:
                isShowState.set(true);
                connect_state.set(getApplication().getResources().getString(R.string.tg_connection_state_connecting));
                break;
            default:
                break;
        }
    }

    public void setContext(Context mContext) {
        this.mContext = mContext;
    }
    private ChatComparator chatComparator = null;
    public void resetChatList() {
        chatList.get().clear();
        List<ChatInfo> list = TelegramManager.getTelegramManager().getTgData().getChatList();
        if (!Common.isEmpty(list)) {
            for (Iterator<ChatInfo> it = list.iterator(); it.hasNext();) {
                ChatInfo chat = it.next();
                if (!chat.isGroup()&&chat.id == UserInfo.getUserInfo().id) {
                    it.remove();
                }else if (chat.lastMessage == null&&!chat.isSecretChat()){
                    it.remove();
                }else if(chat.isSuperGroup()&&TelegramManager.getTelegramManager().getTgData().isInNotMemberSuperGroups(chat)){
                    it.remove();
                }
            }
            if (!Common.isEmpty(list)) {
                if(chatComparator==null){
                    chatComparator = new ChatComparator();
                }
                Collections.sort(list, chatComparator);
            }
            chatList.get().addAll(list);
        }

        //刷新列表
        if (recentMessageListAdapter != null){
            recentMessageListAdapter.notifyDataSetChanged();
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                if(chatList.get().size() == 0){
                    isEmptyView.set(true);
                }else {
                    isEmptyView.set(false);
                }
            }
        },500);
        //刷新未读总数
        refreshTotalUnreadCount();
    }

    //刷新未读总数
    public void refreshTotalUnreadCount() {
        int totalUnreadCount = 0;
        for (ChatInfo chat : chatList.get()) {
            if (chat.unread_count > 0) {
                totalUnreadCount += chat.unread_count;
                TelegramManager.getTelegramManager().getChatMessageCount(mContext, chat.id, new TgResultBlock<Integer>() {

                    @Override
                    public void onResult(Map<String, Object> request, JsonObject response, Integer obj) {
                        int temp = chat.unread_mention_count;
                        chat.unread_mention_count = obj;
                        if(temp!=obj){
                            recentMessageListAdapter.notifyChat(chat);
                        }
                    }

                    @Override
                    public void onTimeout(Map<String, Object> request) {

                    }
                });
            } else {
                chat.unread_mention_count = 0;
            }
        }
        UserInfo.getUserInfo().msgUnreadTotalCount = totalUnreadCount;
        EventBus.getDefault().post(TgEvent.event(TelegramManager.EUser_TgEvent.EUser_Td_Message_Total_Unread_Changed, totalUnreadCount));
    }


    public void clickDelete(MsgFragment fragment, ChatInfo chat) {//删除会话
        AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
        dialog.setTitle(R.string.dialog_title_tip).setMessage(App.getInstanse().getString(R.string.delete_msg_question));
        dialog.setPositiveButton(R.string.dialog_ok,
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        doDeleteChat(fragment, chat);
                    }
                });
        dialog.setNegativeButton(R.string.dialog_cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog.show();
    }

    public void doDeleteChat(MsgFragment fragment, ChatInfo chat) {
        if(fragment!=null){
            fragment.showDialog();
        }
        if(chat.isSecretChat()){
            TelegramManager.getTelegramManager().closeSecretChat(mContext, chat.secretChatId(), new TgResultBlock<TgResponse>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                    doRealDeleteChat(fragment,chat);
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    doRealDeleteChat(fragment,chat);
                }
            });
        }else if(chat.isSuperGroup()){
            TelegramManager.getTelegramManager().getSuperGroupInfo(mContext, chat.superGroupId(), new TgResultBlock<SuperGroupInfo>() {
                @Override
                public void onResult(Map<String, Object> request, JsonObject response, SuperGroupInfo obj) {
                    if(obj!=null&&!TextUtils.isEmpty(obj.username)){
                        TelegramManager.getTelegramManager().leaveGroup(mContext, chat.id, new TgResultBlock<TgResponse>() {
                            @Override
                            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                                if(fragment!=null){
                                    fragment.dismissDialog();
                                }

                                if (!obj.ok) {
                                    showErrorTip(App.getInstanse().getString(R.string.request_error) + obj.errString);
                                }
                            }

                            @Override
                            public void onTimeout(Map<String, Object> request) {
                                if(fragment!=null) {
                                    fragment.dismissDialog();
                                }
                                showErrorTip(App.getInstanse().getString(R.string.request_error));
                            }
                        });
                    }else{
                        doRealDeleteChat(fragment,chat);
                    }
                }

                @Override
                public void onTimeout(Map<String, Object> request) {
                    doRealDeleteChat(fragment,chat);
                }
            });
        }else{
            doRealDeleteChat(fragment,chat);
        }
    }

    private void doRealDeleteChat(MsgFragment fragment,ChatInfo chat) {
        TelegramManager.getTelegramManager().deleteChatHistory(mContext, chat.id, true, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                if(fragment!=null) {
                    fragment.dismissDialog();
                }
                if (!obj.ok) {
                    showErrorTip(App.getInstanse().getString(R.string.request_error) + obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                if(fragment!=null) {
                    fragment.dismissDialog();
                }
                showErrorTip(App.getInstanse().getString(R.string.request_error));
            }
        });
    }

    public void clickPin(MsgFragment fragment, ChatInfo chat) {//置顶或者取消置顶
        fragment.showDialog();
        TelegramManager.getTelegramManager().toggleChatIsPinned(mContext, chat.id, !chat.is_pinned, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                fragment.dismissDialog();
                if (!obj.ok) {
                    showErrorTip(App.getInstanse().getString(R.string.request_error) + obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                fragment.dismissDialog();
                showErrorTip(App.getInstanse().getString(R.string.request_error));
            }
        });
    }

    public void clickMute(MsgFragment fragment, ChatInfo chat) {//静音
        fragment.showDialog();
        TelegramManager.getTelegramManager().toggleChatDisableNotification(mContext, chat.id, !chat.default_disable_notification, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                fragment.dismissDialog();
                if (!obj.ok) {
                    showErrorTip(App.getInstanse().getString(R.string.request_error) + obj.errString);
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                fragment.dismissDialog();
                showErrorTip(App.getInstanse().getString(R.string.request_error));
            }
        });
    }

    public void setadapter(RecentMessageListAdapter recentMessageListAdapter) {
        this.recentMessageListAdapter = recentMessageListAdapter;
    }
}
